#include "Mailer.h"
#include <iostream>

Mailer::Mailer():Thread(sendRecieve,this)
{
mailbox=new UnBoundedMailBox();
}

Mailer::~Mailer()
{
delete mailbox;
}

void* Mailer::sendRecieve(void* arg)
{
//printf("in while of mailer");
//(UnBoundedMailBox*)arg=new UnBoundedMailBox();//(UnBoundedMailBox)arg;
Mailer* mailer=(Mailer*)arg;
Message* msg;	
int i;
//Kernel* system=Kernel::getInsatnce();
	while(true){
		//printf("in while of mailer\n");
		msg=mailer->mailbox->Extract();
		i=msg->to();
		mailer->holding=i;
		//cout<< "i is "<< i<< endl;
		//cout<< "holding is "<< mailer->holding<<endl;
		mailer->m_nodesMailboxes[i]->PutIn(msg);//i is the index of the node thread needs to enter the message to
		//cout<< msg->from() << " to " << msg->to() <<" has been
//putted in the nodes mailbox\n";
	}
}


void Mailer::insert(int DestinationNodeID, Message* msg)
{
//if (msg->type()==1)
  //  cout<< msg->from() << " sent message to " << msg->to() <<" via mailer insert\n";
	mailbox->PutIn(msg);
}

void Mailer::clearMailBoxes()
{
	//m_nodesMailboxes.emptyAll();//we need to know how to clear the mailboxes of the other nodes either we learn the hard way by googling or well use map ds for manipulating and then empty all mailboxes
}

void Mailer::setNodesMailBoxes(map<int,BoundedMailBox*> nodesMailboxes, int numOfMailBoxes)
{
	m_nodesMailboxes=nodesMailboxes;
	m_numOfMailBoxes=numOfMailBoxes;
}

int Mailer::getMaxLength()
{
	return mailbox->getMaxSize();
}

int Mailer::getMailBoxSize()
{
	return mailbox->getSize();
}

void Mailer::emptyMailBox()
{
	mailbox->cleanMailBox();
}

BoundedMailBox* Mailer::getMailbox(int i)
{
	//cout<< "here\n";
	return m_nodesMailboxes[i];
}	

bool Mailer::isDeadlocked(int id) {
//cout<< "id is " << id << endl;
//cout<< "holding is "<< holding<<endl;
return (holding==id);

};



